package cn.edu.zut.qixiang.controller;

import cn.edu.zut.qixiang.entity.WeatherData;
import cn.edu.zut.qixiang.repository.WeatherDataRepository;
import cn.edu.zut.qixiang.service.RealTimeWeatherProducerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 86178
 */
@RestController
@RequestMapping("/api/realtime-weather")
@Slf4j
public class RealTimeWeatherController {

    @Autowired
    private RealTimeWeatherProducerService realTimeWeatherService;

    @Autowired
    private WeatherDataRepository weatherDataRepository;

    private static final DateTimeFormatter DATE_TIME_FORMATTER =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter TIME_FORMATTER =
            DateTimeFormatter.ofPattern("HH:mm");

    /**
     * 获取指定区域的最近气象数据
     */
    @GetMapping("/district/{districtName}")
    public Map<String, Object> getDistrictRecentData(@PathVariable String districtName) {
        log.debug("获取区域实时数据: {}", districtName);

        Map<String, Object> result = new HashMap<>();

        try {
            // 首先尝试从实时服务获取数据
            Map<String, Object> producerData = realTimeWeatherService.getRecentWeatherData(districtName);

            if (producerData.containsKey("error") || !producerData.containsKey("data")) {
                // 如果实时服务没有数据，从MySQL获取
                log.info("从实时服务未获取到数据，尝试从MySQL获取: {}", districtName);
                List<WeatherData> dbData = getRecentDataFromMySQL(districtName, 10);

                if (!dbData.isEmpty()) {
                    result.put("district", districtName);
                    result.put("data", convertToFrontendFormat(dbData));
                    result.put("lastUpdate", LocalDateTime.now().format(DATE_TIME_FORMATTER));
                    result.put("source", "mysql");
                    result.put("dataCount", dbData.size());
                } else {
                    result.put("error", "暂无该区域的气象数据: " + districtName);
                    result.put("source", "none");
                }
            } else {
                // 使用生产者服务的数据
                result.putAll(producerData);
                result.put("source", "realtime");
            }

        } catch (Exception e) {
            log.error("获取区域气象数据失败: {}", districtName, e);
            result.put("error", "获取数据失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 从MySQL获取最近数据
     */
    private List<WeatherData> getRecentDataFromMySQL(String districtName, int count) {
        try {
            Pageable pageable = PageRequest.of(0, count);
            List<WeatherData> data = weatherDataRepository.findRecentByDistrict(districtName, pageable);

            // 按时间正序排列（从旧到新）
            data.sort(Comparator.comparing(WeatherData::getTimestamp));

            return data;
        } catch (Exception e) {
            log.error("从MySQL获取数据失败: {}", districtName, e);
            return Collections.emptyList();
        }
    }

    /**
     * 将数据库实体转换为前端需要的格式
     */
    private List<Map<String, Object>> convertToFrontendFormat(List<WeatherData> dbData) {
        return dbData.stream().map(entity -> {
            Map<String, Object> data = new HashMap<>();
            data.put("district", entity.getDistrict());
            data.put("timestamp", entity.getTimestamp().format(DATE_TIME_FORMATTER));
            data.put("timeDisplay", entity.getTimestamp().format(TIME_FORMATTER));
            data.put("temperature", entity.getTemperature());
            data.put("humidity", entity.getHumidity());
            data.put("windSpeed", entity.getWindSpeed());
            data.put("windDirection", entity.getWindDirection());
            data.put("pressure", entity.getPressure());
            data.put("precipitation", entity.getPrecipitation());
            data.put("dataId", entity.getId()); // 添加唯一标识
            return data;
        }).collect(Collectors.toList());
    }

    /**
     * 获取所有区域的当前数据快照
     */
    @GetMapping("/all-districts")
    public Map<String, Object> getAllDistrictsCurrentData() {
        log.debug("获取所有区域当前数据");
        return realTimeWeatherService.getAllDistrictsCurrentData();
    }

    /**
     * 获取服务状态
     */
    @GetMapping("/status")
    public Map<String, Object> getServiceStatus() {
        return realTimeWeatherService.getServiceStatus();
    }

    /**
     * 获取MySQL中的数据统计
     */
    @GetMapping("/mysql-stats")
    public Map<String, Object> getMySQLStats() {
        Map<String, Object> stats = new HashMap<>();
        try {
            long totalRecords = weatherDataRepository.count();
            List<WeatherData> latestRecords = weatherDataRepository.findLatestAllDistricts();

            stats.put("totalRecords", totalRecords);
            stats.put("latestRecordCount", latestRecords.size());
            stats.put("latestUpdate", LocalDateTime.now().format(DATE_TIME_FORMATTER));
            stats.put("status", "connected");

            // 各区域数据统计
            Map<String, Long> districtStats = new HashMap<>();
            List<String> districts = Arrays.asList("中原区", "二七区", "管城回族区", "金水区", "上街区",
                    "惠济区", "中牟县", "巩义市", "荥阳市", "新密市", "新郑市", "登封市");

            for (String district : districts) {
                Long count = weatherDataRepository.countByDistrict(district);
                districtStats.put(district, count);
            }
            stats.put("districtStats", districtStats);

        } catch (Exception e) {
            log.error("获取MySQL统计失败", e);
            stats.put("error", e.getMessage());
            stats.put("status", "disconnected");
        }
        return stats;
    }

    /**
     * 手动触发数据生成（测试用）
     */
    @PostMapping("/generate-test-data")
    public Map<String, Object> generateTestData() {
        Map<String, Object> result = new HashMap<>();
        try {
            // 调用服务方法生成测试数据
            realTimeWeatherService.generateRealTimeData();
            result.put("success", true);
            result.put("message", "测试数据生成成功");
            result.put("timestamp", LocalDateTime.now().format(DATE_TIME_FORMATTER));
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "测试数据生成失败: " + e.getMessage());
        }
        return result;
    }
}